import React, { useState, useEffect } from "react";
import { Node } from "reactflow";
import "./NodeConfigPanel.css";

interface ConfigField {
  key: string;
  label: string;
  type: string;
  options?: string[];
  tooltip?: string;
  min?: number;
  max?: number;
  step?: number;
}

interface NodeConfig {
  [key: string]: string | number | boolean;
}

interface NodeConfigPanelProps {
  node: Node;
  onClose: () => void;
  updateNodeConfig: (config: NodeConfig) => void;
  onDeleteNode: () => void;
}

const NodeConfigPanel: React.FC<NodeConfigPanelProps> = ({
  node,
  onClose,
  updateNodeConfig,
  onDeleteNode,
}) => {
  const [config, setConfig] = useState<NodeConfig>(node.data.config || {});
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  useEffect(() => {
    setConfig(node.data.config || {});
  }, [node.id, node.data.config]);

  const getNodeColor = () => {
    switch (node.type) {
      case "inputNode":
        return "var(--node-input-color)";
      case "aiNode":
        return "var(--node-ai-color)";
      case "processorNode":
        return "var(--node-processor-color)";
      case "outputNode":
        return "var(--node-output-color)";
      default:
        return "#718096";
    }
  };

  const getConfigFields = (): ConfigField[] => {
    switch (node.type) {
      case "inputNode":
        return [
          {
            key: "inputType",
            label: "输入类型",
            type: "select",
            options: ["text", "file", "api"],
            tooltip: "选择数据输入类型",
          },
          {
            key: "description",
            label: "描述",
            type: "text",
            tooltip: "输入节点的功能描述",
          },
          {
            key: "required",
            label: "是否必填",
            type: "checkbox",
            tooltip: "标记为必填项",
          },
        ];
      case "aiNode":
        return [
          {
            key: "modelName",
            label: "模型名称",
            type: "select",
            options: ["GPT-4", "BERT", "LLaMA", "Claude"],
            tooltip: "选择AI模型",
          },
          {
            key: "temperature",
            label: "温度",
            type: "range",
            min: 0,
            max: 1,
            step: 0.1,
            tooltip: "控制输出的随机性，越高越随机",
          },
          {
            key: "apiKey",
            label: "API密钥",
            type: "password",
            tooltip: "连接模型API所需的密钥",
          },
          {
            key: "maxTokens",
            label: "最大Token数",
            type: "number",
            tooltip: "生成内容的最大长度",
          },
          {
            key: "systemPrompt",
            label: "系统提示词",
            type: "textarea",
            tooltip: "定义系统角色和行为的提示词",
          },
        ];
      case "processorNode":
        return [
          {
            key: "operation",
            label: "操作类型",
            type: "select",
            options: ["转换", "筛选", "合并", "分割"],
            tooltip: "数据处理的操作类型",
          },
          {
            key: "script",
            label: "处理脚本",
            type: "textarea",
            tooltip: "自定义处理脚本，用于数据转换",
          },
          {
            key: "isAsync",
            label: "异步处理",
            type: "checkbox",
            tooltip: "是否异步执行处理操作",
          },
        ];
      case "outputNode":
        return [
          {
            key: "outputType",
            label: "输出类型",
            type: "select",
            options: ["text", "json", "file", "api"],
            tooltip: "输出数据格式",
          },
          {
            key: "destination",
            label: "目标位置",
            type: "text",
            tooltip: "输出目标，如API地址、文件路径等",
          },
          {
            key: "formatTemplate",
            label: "格式模板",
            type: "textarea",
            tooltip: "定义数据输出的格式",
          },
        ];
      default:
        return [];
    }
  };

  const handleChange = (key: string, value: string | number | boolean) => {
    setConfig((prev) => ({ ...prev, [key]: value }));
  };

  const handleSave = () => {
    updateNodeConfig(config);
    onClose();
  };

  const handleDeleteClick = () => {
    setShowDeleteConfirm(true);
  };

  const confirmDelete = () => {
    onDeleteNode();
    setShowDeleteConfirm(false);
  };

  const cancelDelete = () => {
    setShowDeleteConfirm(false);
  };

  const renderField = (field: ConfigField) => {
    switch (field.type) {
      case "text":
      case "password":
        return (
          <input
            type={field.type}
            value={
              typeof config[field.key] === "boolean"
                ? String(config[field.key])
                : config[field.key]?.toString() || ""
            }
            onChange={(e) => handleChange(field.key, e.target.value)}
            placeholder={`输入${field.label}...`}
          />
        );
      case "number":
        return (
          <input
            type="number"
            value={config[field.key]}
            onChange={(e) =>
              handleChange(field.key, parseInt(e.target.value) || 0)
            }
            placeholder={`输入${field.label}...`}
            min={field.min}
            max={field.max}
          />
        );
      case "select":
        return (
          <select
            value={config[field.key] || ""}
            onChange={(e) => handleChange(field.key, e.target.value)}
          >
            <option value="">请选择{field.label}</option>
            {field.options?.map((option: string) => (
              <option key={option} value={option}>
                {option}
              </option>
            ))}
          </select>
        );
      case "range":
        return (
          <div className="range-container">
            <input
              type="range"
              min={field.min}
              max={field.max}
              step={field.step}
              value={
                typeof config[field.key] === "number"
                  ? (config[field.key] as number)
                  : field.min ?? 0
              }
              onChange={(e) =>
                handleChange(field.key, parseFloat(e.target.value))
              }
              className="range-input"
            />
            <span className="range-value-display">
              {config[field.key] || field.min}
            </span>
          </div>
        );
      case "textarea":
        return (
          <textarea
            value={config[field.key] || ""}
            onChange={(e) => handleChange(field.key, e.target.value)}
            rows={4}
            placeholder={`输入${field.label}...`}
          />
        );
      case "checkbox":
        return (
          <div className="checkbox-container">
            <input
              type="checkbox"
              checked={!!config[field.key]}
              onChange={(e) => handleChange(field.key, e.target.checked)}
              id={`checkbox-${field.key}`}
            />
            <label htmlFor={`checkbox-${field.key}`} className="checkbox-label">
              {field.label}
            </label>
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div className="config-panel">
      <div
        className="config-header"
        style={{ borderBottomColor: getNodeColor() }}
      >
        <h3 style={{ color: getNodeColor() }}>节点配置: {node.data.label}</h3>
        <button className="config-close-btn" onClick={onClose}>
          ×
        </button>
      </div>

      {showDeleteConfirm ? (
        <div className="delete-confirm">
          <p>确定要删除此节点吗？这将同时删除与其相连的所有连接。</p>
          <div className="delete-confirm-actions">
            <button className="delete-btn confirm" onClick={confirmDelete}>
              确认
            </button>
            <button className="delete-btn cancel" onClick={cancelDelete}>
              取消
            </button>
          </div>
        </div>
      ) : (
        <div>
          {getConfigFields().map((field) => (
            <div key={field.key} className="config-field">
              <div className="field-header">
                <label>{field.label}</label>
                {field.tooltip && (
                  <div className="tooltip tooltip-icon" title={field.tooltip}>
                    ℹ️
                  </div>
                )}
              </div>
              {renderField(field)}
            </div>
          ))}

          <div className="config-actions">
            <button className="save-btn" onClick={handleSave}>
              保存配置
            </button>
          </div>
          <div className="delete-section">
            <button onClick={handleDeleteClick} className="delete-node-btn">
              删除节点
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default NodeConfigPanel;
